package com.feidee.fdhadoop.hbase;

import com.feidee.fdcommon.configuration.CustomConfiguration;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HBaseUtilForV1 {
    protected static final Logger logger = LoggerFactory.getLogger(HBaseUtilForV1.class);
    private static Connection conn;

    // 初始化连接
    static{
        try {
            Configuration conf = HBaseConfiguration.create();
            conf.set("hbase.zookeeper.property.clientPort", CustomConfiguration.getString("hbase.zookeeper.property.clientPort","2181"));
            conf.set("hbase.zookeeper.quorum", CustomConfiguration.getString("hbase.zookeeper.quorum",""));
            conf.set("hbase.client.scanner.caching", CustomConfiguration.getString("hbase.client.scanner.caching","100"));
            conf.set("hbase.rpc.timeout", CustomConfiguration.getString("hbase.rpc.timeout","6000"));//rpc的超时时间
            conf.set("ipc.socket.timeout", CustomConfiguration.getString("ipc.socket.timeout","2000"));//socket建立链接的超时时间，应该小于或者等于rpc的超时时间
            conf.set("hbase.client.retries.number", CustomConfiguration.getString("hbase.client.retries.number","3"));//重试次数
            conf.set("hbase.client.pause", CustomConfiguration.getString("hbase.client.pause","100"));//重试休眠时间，默认为1s
            conf.set("zookeeper.recovery.retry", CustomConfiguration.getString("zookeeper.recovery.retry","3"));//zk重试次数

            conf.setBoolean("compatible.for.v1",true);
            conn = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            logger.error("HBase Connection init failed ",e);
        }
    }

    /**
     * 获取指定行和列的数据
     *
     * @param tableName
     * @param rowKey
     * @param family
     * @param qualifier
     * @return
     */
    public static String get(String tableName, String rowKey, String family, String qualifier) {
        Table t = null;
        try {
            t = getTable(tableName);
            return HBaseUtilHelper.get(rowKey, family, qualifier, t);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行get异常！", e);
        } finally {
            closeTable(t);
        }
        return null;
    }

    /**
     * 获取指定行的数据
     *
     * @param tableName
     * @param rowKey
     * @return
     */
    public static Map<String, Map<String, String>> get(String tableName, String rowKey) {
        Map<String, Map<String, String>> results = null;
        Table t = null;
        try {
            t = getTable(tableName);
            results = HBaseUtilHelper.get(rowKey, t);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行get异常！", e);
        } finally {
            closeTable(t);
        }
        return results;
    }


    /**
     * 获取指定行和列族的数据
     *
     * @param tableName
     * @param rowKey
     * @param family
     * @return
     */
    public static Map<String, String> get(String tableName, String rowKey, String family) {
        Map<String, String> result = null;
        Table t = null;
        try {
            t = getTable(tableName);
            result = HBaseUtilHelper.get(rowKey, family, t);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行get异常！", e);
        } finally {
            closeTable(t);
        }
        return result;
    }

    /**
     * 获取指定行和部分列的数据
     *
     * @param tableName
     * @param rowKey
     * @param family
     * @param qualifierSet
     * @return
     */
    public static Map<String, String> get(String tableName, String rowKey, String family, Set<String> qualifierSet) {
        Map<String, String> result = null;
        Table t = null;
        try {
            t = getTable(tableName);
            result = HBaseUtilHelper.get(rowKey, family, qualifierSet, t);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行get异常！", e);
        } finally {
            closeTable(t);
        }
        return result;
    }

    /**
     * 其它api不能满足时使用，比如需要使用filter的情况
     *
     * @param tableName
     * @param get
     * @return
     */
    public static Result get(String tableName, Get get) {
        Result result = null;
        Table t = null;
        try {
            t = getTable(tableName);
            result = t.get(get);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行get异常！", e);
        } finally {
            closeTable(t);
        }
        return result;
    }

    /**
     * 其它api不能满足时使用，比如需要使用filter的情况
     *
     * @param tableName
     * @param gets
     * @return
     */
    public static Result[] get(String tableName, List<Get> gets) {
        Result[] results = null;
        Table t = null;
        try {
            t = getTable(tableName);
            results = t.get(gets);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行get异常！", e);
        } finally {
            closeTable(t);
        }
        return results;
    }

    /**
     * 写入单列数据
     *
     * @param tableName
     * @param rowkey
     * @param family
     * @param qualifier
     * @param value
     * @throws Exception
     */
    public static void put(String tableName, String rowkey, String family, String qualifier, String value) throws Exception {
        Table t = null;
        try {
            t = getTable(tableName);
            Put put = new Put(Bytes.toBytes(rowkey));
            put.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier), Bytes.toBytes(value));
            t.put(put);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行put异常！", e);
            throw e;
        } finally {
            closeTable(t);
        }
    }

    /**
     * 写入单行数据
     *
     * @param tableName
     * @param rowkey
     * @param family
     * @param valueMap
     * @throws Exception
     */
    public static void put(String tableName, String rowkey, String family, Map<String, String> valueMap) throws Exception {
        Table t = null;
        try {
            t = getTable(tableName);
            HBaseUtilHelper.put(rowkey, family, valueMap, t);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行put异常！", e);
            throw e;
        } finally {
            closeTable(t);
        }
    }

    /**
     * 写入多行数据
     *
     * @param tableName
     * @param family
     * @param recordList
     * @throws Exception
     */
    public static void put(String tableName, String family, List<Map<String, String>> recordList) throws Exception {
        Table t = null;
        try {
            t = getTable(tableName);
            HBaseUtilHelper.put(family, recordList, t);
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行put异常！", e);
            throw e;
        } finally {
            closeTable(t);
        }
    }

    /**
     * 写入数据，用于不需要value的场景
     *
     * @param tableName
     * @param rowkey
     * @throws Exception
     */
    public static void put(String tableName, String rowkey) throws Exception {
        put(tableName, rowkey, HBaseUtilHelper.DEFAULT_FAMILY);
    }

    /**
     * 写入数据，用于不需要value的场景
     *
     * @param tableName
     * @param rowkey
     * @param family
     * @throws Exception
     */
    public static void put(String tableName, String rowkey, String family) throws Exception {
        Map<String, String> values = new HashMap<>();
        values.put(HBaseUtilHelper.DEFAULT_QUALIFIER, "");
        put(tableName, rowkey, family, values);
    }

    /**
     * 删除指定行的列
     *
     * @param tableName
     * @param rowkey
     * @param family
     * @param qualifier
     * @return
     */
    public static boolean del(String tableName, String rowkey, String family, String qualifier) {
        long start = System.currentTimeMillis();
        Table t = null;
        try {
            t = getTable(tableName);
            Delete del = new Delete(Bytes.toBytes(rowkey));

            if (qualifier != null) {
                del.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
            } else if (family != null) {
                del.addFamily(Bytes.toBytes(family));
            }
            t.delete(del);
            return true;
        } catch (Exception e) {
            logger.error("HBaseUtilForV1执行del异常！", e);
        } finally {
            closeTable(t);
        }
        return false;
    }

    /**
     * 删除指定行
     *
     * @param tableName
     * @param rowKey
     * @return
     */
    public static boolean del(String tableName, String rowKey) {
        return del(tableName, rowKey, null, null);
    }

    /**
     * 删除指定行的列族
     *
     * @param tableName
     * @param rowKey
     * @param family
     * @return
     */
    public static boolean del(String tableName, String rowKey, String family) {
        return del(tableName, rowKey, family, null);
    }

    /**
     * 现有api不满足需求时使用；
     * 由于可能会在线切换集群，所以不要缓存Table；
     *
     * @param table
     * @return
     * @throws Exception
     */
    public static Table getTable(String table) throws Exception {
        try {
            if (conn != null) {
                return conn.getTable(TableName.valueOf(table));
            }
        } catch (Exception e) {
            logger.error("HBaseUtilForV1 get table异常！", e);
            throw e;
        }
        return null;
    }

    public static void closeTable(Table table) {
        if (table != null) {
            try {
                table.close();
            } catch (Exception e) {
                logger.error("HBaseUtilForV1 close table异常！", e);
            }
        }
    }

    /**
     * 进行Admin相关操作时使用；
     * 由于可能会在线切换集群，所以不要缓存Connection；
     */
    public static Connection getConn() {
        return conn;
    }

    public static void close() {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                logger.error("HBaseUtilForV1 关闭连接异常！", e);
            }
        }
    }
}
